<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>service worker</title>
  <link rel="manifest" href="/manifest.json">
  <link rel="stylesheet" href="./style.css">
</head>

<body>
  service worker2323
  <img src="icon.png" alt="">
  <div onclick="push()">推送</div>
  <div id="installBtn">安装</div>
  <div onclick="add()">插入数据</div>
  <div onclick="get()">获取数据</div>
  <div onclick="del()">删除数据</div>
</body>
<script>
  function urlBase64ToUint8Array(base64String) {
    const padding = '='.repeat((4 - (base64String.length % 4)) % 4);
    const base64 = (base64String + padding)
      .replace(/-/g, '+')
      .replace(/_/g, '/');

    const rawData = atob(base64);
    const outputArray = new Uint8Array(rawData.length);

    for (let i = 0; i < rawData.length; ++i) {
      outputArray[i] = rawData.charCodeAt(i);
    }
    return outputArray;
  }
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('/sw.js')
      .then(async (reg) => {
        console.log('SW 注册成功:', reg);
        const result = await fetch('/getKey', {
          method: 'get',
        });
        const data = await result.json()
        console.log(data)
        let subscription = await reg.pushManager.getSubscription();
        if (subscription) {
          await subscription.unsubscribe();
        }
        subscription = await reg.pushManager.subscribe({
          userVisibleOnly: true,
          applicationServerKey: urlBase64ToUint8Array(data.data)
        });
        await fetch('/subscribe', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(subscription)
        });
        reg.update();
      })
      .catch(err => {
        console.error('SW 注册失败:', err);
      });

    // 请求通知权限
    Notification.requestPermission().then(permission => {
      console.log('通知权限:', permission);
    });
  }
  async function push() {
    await fetch("/push")
  }

  let deferredPrompt;

  window.addEventListener('beforeinstallprompt', (e) => {
    console.log(e)
    e.preventDefault(); // 阻止自动弹窗
    deferredPrompt = e;
    // 可以显示自己的“安装到桌面”按钮
    document.querySelector('#installBtn').style.display = 'block';
  });

  document.querySelector('#installBtn').addEventListener('click', async () => {
    deferredPrompt.prompt();
    const { outcome } = await deferredPrompt.userChoice;
    console.log('用户选择结果:', outcome);
    deferredPrompt = null;
  });

  const request = indexedDB.open('myDatabase', 1); // 数据库名 + 版本号
  request.onupgradeneeded = (event) => {
    const db = event.target.result;

    // 创建对象仓库（类似表）
    if (!db.objectStoreNames.contains('users')) {
      const store = db.createObjectStore('users', { keyPath: 'id', autoIncrement: true });
      // 可创建索引
      store.createIndex('name', 'name', { unique: false });
    }
  };

  request.onsuccess = (event) => {
    db = event.target.result;
    console.log('数据库打开成功', db);
  };

  request.onerror = (event) => {
    console.error('打开数据库失败', event.target.error);
  };

  function add() {
    const transaction = db.transaction('users', 'readwrite'); // 读写事务
    const store = transaction.objectStore('users');

    const user = { name: 'Alice', age: 25 };
    const addRequest = store.add(user);

    addRequest.onsuccess = () => console.log('数据添加成功');
    addRequest.onerror = (e) => console.error('添加失败', e);
  }
  function get() {
    const transaction = db.transaction('users', 'readonly');
    const store = transaction.objectStore('users');

    const getRequest = store.get(1); // 按主键获取

    getRequest.onsuccess = (e) => console.log('读取结果', e.target.result);
  }
  function del() {
    const transaction = db.transaction('users', 'readwrite');
    const store = transaction.objectStore('users');

    // 删除主键为 1 的数据
    const deleteRequest = store.delete(1);

    deleteRequest.onsuccess = () => console.log('数据删除成功');
    deleteRequest.onerror = (e) => console.error('删除失败', e);
  }
</script>

</html>